let myNumber=$('#type').val()=='add'?1:''
const setNumber=()=>{
    let myinput=$('input[name="title2"]')
    let Numbers=$(myinput[myinput.length-1]).val()
    myNumber=++Numbers
}
const myI=function (index,obj){

    console.log(index)
    if(index==0){
        setNumber()
        const myDiv=$(obj).parent().parent()
        console.log(myDiv)
        myDiv.append(`
          <div class="layui-form-item">
            <label class="layui-form-label required">床号</label>
            <div class="layui-input-block">
                <input type="number" name="title2" lay-verify="required" autocomplete="off"
                       placeholder="请输入床号" 
                       value="${myNumber}"
                       class="layui-input myInputs">
                <i class="fa fa-close" style="margin: 0 10px;" onclick="myI(1,this)"> </i>
            </div>
        </div>
        `)
    }else if(index==1){
        $(obj).parent().parent().remove()
    }
}

const showTols=()=>{
    let _index=layer.open({
        type: 1,
        title: '搜索获取经纬度',
        maxmin: true,
        area: ['800px', '800px'],
        shadeClose: false,
        content: `
         <iframe src="https://api.map.baidu.com/lbsapi/getpoint/index.html" id="myUrlIframe" width="100%" height="1000"></iframe>
        `,
    });
    layer.full(_index)

}

layui.use(['form'],async function () {
    var form = layui.form;
    var layer = layui.layer;

    _setTitleList=(data)=>{
        $("#title").empty();
        let MyLonLat=''
        if(null!=$("#title").attr('myvalue')&&$("#title").attr('myvalue')!=''){
            MyLonLat=$("#title").attr('myLon')+','+$("#title").attr('myLat')
        }
        console.log('MyLonLat',MyLonLat)
        $("#title").append($('<option>', {
            value: '',
            text: (data.length>0?'加载完成，请选择':'请进行搜索'),
        }))
        console.log('data',data)
        if(data&&data.length>0){
            data.forEach(item=>{
                $("#title").append($('<option>', {
                    value: item.IsLocal?item.value:(item.address+'-'+item.name+','+item.lonlat),
                    text: item.IsLocal?item.text:(item.address+'-'+item.name),
                    selected:item.lonlat==MyLonLat
                }))
            })
        }

        $("#title").attr("disabled", $("#title").prop('disabled'));
        form.render('select');
        hindLoading()
    }
    var localsearch,map;
    let isTrueMap=false
    _initMY=async (number=3)=>{
        try {
            map =null==map?(new T.Map("myMap")):map;
            map.centerAndZoom(new T.LngLat(113.014661, 28.143054), 12);
            localsearch = new T.LocalSearch(map, {
                pageCapacity: 100,	//每页显示的数量
                onSearchComplete: (result) => {
                    _setTitleList(result.getSuggests())
                }
            });
            localsearch.search($('#title0').val(),4)
            isTrueMap=true
        }catch (e){
            if(number>0){
                    //尝试加载js
                   await $.getScript("http://api.tianditu.gov.cn/api?v=4.0&tk=37ab2744b4aabf3ca520baeffc2244d6")
                        .then(function() {
                            isTrueMap=true
                            //必须等待
                            setTimeout(()=>{
                                _initMY(0)},500)
                        }).fail(function(error) {
                           isTrueMap=false
                           _initMY(--number)
                       });
            }
            if(!isTrueMap){
                layer.msg("地图服务出现问题,请刷新页面尝试，或者联系管理员")
            }
        }
    }
   await _initMY()

    $('#inputButton').click(()=>{
        var tempInput = $("<textarea>");
        tempInput.val($('#title0').val());
        $("body").append(tempInput);
        tempInput.select();
        document.execCommand("copy");
        tempInput.remove();
        parent.layer.msg('已经复制到粘贴板，右键粘贴或者ctrl+V进行复制，查询')
        console.log($('#title0').val(),'====')
        showTols()
    })
    $('#title0')[0].addEventListener('keyup',_debounce ( (event)=>{
        if(isTrueMap){
            showLoading()
            localsearch.search($('#title0').val(),4)
        }else{
            //默认经纬度云集大厦
            _setTitleList([{
                value:$('#title0').val()+',113.002320,28.140550',
                text:  $('#title0').val(),
                IsLocal:true
            }])
        }
    },1000))


    if(null!=$("#title").attr('myvalue')&&$("#title").attr('myvalue')!=''){
        $('#title0').val($('#title0').val().split('-')[1])

    }else{
        _setTitleList([])
    }

    //提交事件
    form.on('submit(submit)', function (data) {
        const myDatas= {
            name:data.field.title.split(',')[0],
            buildNumber:data.field.title1,
            bedCode:[],
            lon:data.field.title.split(',')[1],
            lat:data.field.title.split(',')[2],
        }
        let myinput=$('input[name="title2"]'),Url=''
        for (let i = 0; i < myinput.length; i++) {
            myDatas.bedCode.push($(myinput[i]).val())
        }
        console.log(myDatas)
        if($('#type').val()=='add'){
            Url='/jzweb/jazHouseTypes/saveHouseType'
        }
        else{
             Url='/jzweb/jazHouseTypes/updateHouseType'
            myDatas.id=$('#dataId').val()
        }
        AjaxPost(Url, myDatas).then(function (response) {
            parent.layer.msg("操作成功");
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layer.close(index);
            parent.load();
        }).catch(error => {
            layer.msg(error.msg)
        })
        return false;
    });


});